#include "modbuswig.h"
#include "ui_modbuswig.h"

#define TOPIC_CTL_DOWN      "/app/control/down"
#define TOPIC_DATA_UP       "/app/data/up"


ModbusWig::ModbusWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ModbusWig)
{
    ui->setupUi(this);

    customPlot = new QCustomPlot(this);

    connect(ui->pushButtonTmp,SIGNAL(clicked()),this,SLOT(clickSendTmpCommandSlot()));

    connect(GlobalVal::mqtt,SIGNAL(dataUpSignal(QByteArray)),this,SLOT(handleMqttMessage(QByteArray)));
}

ModbusWig::~ModbusWig()
{
    delete ui;
}

void ModbusWig::clickSendTmpCommandSlot()
{
    //获取时间
    QDateTime timeStart = ui->dateTimeEditStart->dateTime();
    QDateTime timeEnd = ui->dateTimeEditEnd->dateTime();
    qint64 time1 = timeStart.toMSecsSinceEpoch();
    qint64 time2 = timeEnd.toMSecsSinceEpoch();

    qDebug() << "time 1" << time1;
    qDebug() << "time 2" << time2;

    QJsonArray limitArray;
    limitArray.append(time1);
    limitArray.append(time2);

    QJsonObject json;
    QJsonObject data;
    data["key"] = 309;
    data["limit"] = limitArray;
    json["type"] = 4;
    json["data"] = data;

    QJsonDocument doc(json);
    QByteArray payload = doc.toJson();

    qDebug() << "payload" << payload;
    QMQTT::Message message;
    message.setTopic(TOPIC_CTL_DOWN); //设置主题
    message.setPayload(payload);//负载
    quint16 messageId = GlobalVal::mqtt->publish(message);
}

void ModbusWig::clickSendHumCommandSlot()
{

    QDateTime timeStart = ui->dateTimeEditStart->dateTime();
    QDateTime timeEnd = ui->dateTimeEditEnd->dateTime();
    qint64 time1 = timeStart.toMSecsSinceEpoch();
    qint64 time2 = timeEnd.toMSecsSinceEpoch();

    QJsonArray limitArray;
    limitArray.append(time1);
    limitArray.append(time2);

    QJsonObject json;
    QJsonObject data;
    data["key"] = 310;
    data["limit"] = limitArray;
    json["type"] = 4;
    json["data"] = data;

    QJsonDocument doc(json);
    QByteArray payload = doc.toJson();
    QMQTT::Message message;
    message.setTopic(TOPIC_CTL_DOWN); //设置主题
    message.setPayload(payload);//负载
    quint16 messageId = GlobalVal::mqtt->publish(message);
}

void ModbusWig::clickSendCo2CommandSlot()
{
    QDateTime timeStart = ui->dateTimeEditStart->dateTime();
    QDateTime timeEnd = ui->dateTimeEditEnd->dateTime();
    qint64 time1 = timeStart.toMSecsSinceEpoch();
    qint64 time2 = timeEnd.toMSecsSinceEpoch();

    QJsonArray limitArray;
    limitArray.append(time1);
    limitArray.append(time2);

    QJsonObject json;
    QJsonObject data;
    data["key"] = 305;
    data["limit"] = limitArray;
    json["type"] = 4;
    json["data"] = data;

    QJsonDocument doc(json);
    QByteArray payload = doc.toJson();
    QMQTT::Message message;
    message.setTopic(TOPIC_CTL_DOWN); //设置主题
    message.setPayload(payload);//负载
    quint16 messageId = GlobalVal::mqtt->publish(message);
}

void ModbusWig::handleMqttMessage(const QByteArray &message)
{
    QJsonDocument doc = QJsonDocument::fromJson(message);
    QJsonObject jsonObj = doc.object();

    QVector<double> timeVector;
    QVector<double> valVector;

    int type = jsonObj.value("type").toInt();
    int result = jsonObj.value("result").toInt();
    int key = jsonObj.value("key").toInt();

    QCustomPlot *customPlot = NULL; // 声明 customPlot 指针

    if (key == 309)
    {
        customPlot = new QCustomPlot(ui->widgetTmp);
    }
    else if (key == 310)
    {
        customPlot = new QCustomPlot(ui->widgetHum);
    }
    else if (key == 305)
    {
        customPlot = new QCustomPlot(ui->widgetCo2);
    }
    else
    {

    }

    QVBoxLayout *layout = new QVBoxLayout(customPlot->parentWidget());
    layout->addWidget(customPlot);
    customPlot->parentWidget()->setLayout(layout);

    customPlot->clearPlottables();

    QCPGraph *graph = customPlot->addGraph();
    QJsonArray dataArray = jsonObj.value("data").toArray();
    for (int i = 0; i < dataArray.size(); ++i)
    {
        QJsonValue value = dataArray.at(i);
        QJsonObject dataObj = value.toObject();

        qint64 time = dataObj.value("time").toVariant().toLongLong();
        QString valStr = dataObj.value("val").toString();
        bool ok;
        double val = valStr.toDouble(&ok);
        if (!ok) {
            continue;
        }

        timeVector.append(time);
        valVector.append(val);
    }

    graph->setData(timeVector, valVector);
    customPlot->xAxis->setLabel("Time");
    customPlot->yAxis->setLabel("Value");

    customPlot->xAxis->setRange(timeVector.first(), timeVector.last());
    QSharedPointer<QCPAxisTickerDateTime> dateTimeTicker(new QCPAxisTickerDateTime);
    dateTimeTicker->setDateTimeFormat("yyyy-MM-dd hh:mm:ss");
    customPlot->xAxis->setTicker(dateTimeTicker);

    customPlot->yAxis->setRange(*std::min_element(valVector.constBegin(), valVector.constEnd()),
                                *std::max_element(valVector.constBegin(), valVector.constEnd()));

    customPlot->replot();
}
